import sys
import util

""" Similarity function desribed in the paper  
 Froehlich, J., Krumm, J., Route Prediction from Trip Observations,  
 In Society of Automative Engineers World Congress Report, April, 2008. """

def similarityFunction(routeA, routeB):
    totalDistAB = 0
    routeBplace = 0
    for pt in routeA:
        minDist = float('inf')
        routeBPointsToTry = range(routeBplace,len(routeB))
        for numB in routeBPointsToTry:
            dist = util.getApproxDistanceKM(pt, routeB[numB])
            if dist < minDist:
                minDist     = dist
                routeBplace = numB
        totalDistAB += minDist
    scoreAB = totalDistAB * 1.0 / len(routeA)
    
    totalDistBA = 0
    routeAplace = 0
    for pt in routeB:
        minDist = float('inf')
        routeAPointsToTry = range(routeAplace, len(routeA))
        for numA in routeAPointsToTry:
            dist = util.getApproxDistanceKM(pt, routeA[numA])
            if dist < minDist:
                minDist = dist
                routeAplace = numA
        totalDistBA += minDist
    scoreBA = totalDistBA * 1.0 / len(routeB)
    
    return (scoreAB + scoreBA) / 2.0

""" OLD TEST FUNCTION """

def run(traceA = "sampleGPS.txt", traceB = "sampleGPS.txt", delimiter = ','):
    print "STARTING"
    
    # f should be a file containing the GPS coordinates in the format
    # latitude longitude
    f = open(traceA, "rb")
    lines = [x.replace('\r\n','') for x in f]
    f.close()
    
    traceA = []
    for coords in lines:
        temp = coords.split(delimiter)
        traceA.append([eval(temp[0]), eval(temp[1])])

    f = open(traceB, "rb")
    lines = [x.replace('\r\n','') for x in f]
    f.close()
    
    traceB = []
    for coords in lines:
        temp = coords.split(delimiter)
        traceB.append([eval(temp[0]), eval(temp[1])])

    a = similarityFunction(traceA, traceB)
    
    print a
    
    print "FINISHED"
    
if __name__ == "__main__":
    run(sys.argv[1], sys.argv[2])